package com.thitech.sif.interceptor;

import com.thitech.sif.AbsOutput;
import com.thitech.sif.Executor;
import com.thitech.sif.context.AbsContext;
import com.thitech.sif.exception.OutputException;
import com.thitech.sif.exception.ServiceExecuteException;
import com.thitech.sif.returntype.ReturnType;
import com.thitech.sif.utils.i18n.Messages;
import com.thitech.sif.utils.log.LogBuilder;

/**
 * 异常处理默认拦截器
 * @author shisheng.lian
 * @date 2014-8-6
 *
 */
public class ExceptionInterceptor extends AbsInterceptorHandler{

	@Override
	public boolean beforeInvoke(Executor executor)
			throws Exception {
		return true;
	}

	@Override
	public void afterInvoke(Executor executor, AbsOutput output, Throwable e) throws Exception {
		String businessId = executor.getBusinessId();
		String ticket = executor.getTicket();
		String serviceId = executor.getServiceId();
		
		if(null != e){
			String systemName = "";
			String serviceName = "";
			AbsContext ctx = executor.getContext();
			if (null != ctx) {
				systemName = ctx.getSystemName();
				serviceName = ctx.getServiceName();
			}
			
			String message = Messages.getMessage("sif.service.invoke.exception", new String[]{systemName, serviceName, serviceId, businessId, ticket});
			
			
			//如果异常为 ServiceExecuteException则表明服务调用异常，如果是OutputException，则表明有可能服务调用过并且是异常
			if ((e instanceof ServiceExecuteException) || (e instanceof OutputException)) {
				updateSifReturn(ReturnType.UE, message, output);
			} else {
				//其它的异常都是没有调用过服务，直接视为失败
				updateSifReturn(ReturnType.TE, message, output);
			}
			getLogger().error(LogBuilder.getLogMsg(executor, "ExceptionInterceptor--afterInvoke--exception not null"), e);
		} else {
			getLogger().debug(LogBuilder.getLogMsg(executor, "ExceptionInterceptor--afterInvoke--no exception"));
		}
	}
}
